package org.simple_framework.inject;

import lombok.extern.slf4j.Slf4j;
import org.simple_framework.core.BeanFactory;
import org.simple_framework.inject.annotation.Autowired;
import org.simple_framework.util.LoadBeanUtil;
import org.simple_framework.util.VerifyUtil;

import java.lang.reflect.Field;

/**
 * @author wxc
 * @date 2021年10月07日 11:00
 * 为创建好的对象进行IOC
 */
@Slf4j
public class DependencyInjector {

    public static void main(String[] args) {

    }

    public static void doIoc(Class<?> clazz, Object o, BeanFactory beanFactory) {
        Field[] fields = clazz.getDeclaredFields();
        if (!VerifyUtil.isEmpty(fields)) {
            for (Field field : fields) {
                if (field.isAnnotationPresent(Autowired.class)) {
                    Class<?> fieldType = field.getType();
                    Object fieldValue = beanFactory.getBean(fieldType);
                    if (fieldValue == null)
                        throw new RuntimeException("unable to inject relevant type，target fieldClass is:" + field.getName());
                    LoadBeanUtil.fieldInject(field, o, fieldValue, true);
                    log.debug("inject {} object {} value {} success", field, o, fieldValue);
                }
            }
        }
    }
}
